package controller

import (
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/gin-gonic/gin"
	"math/rand"
	"my_chat/setting"
	"time"
)

func LoadFileOss(c *gin.Context) {
	////限制上传最大尺寸
	//r.MaxMultipartMemory = 8 << 20

	//获得上传的源文件s
	srcfile, _, err := c.Request.FormFile("file")
	if err != nil {
		RespFail(c, err.Error())
		return
	}
	ossConf := setting.Conf.AliyunOss
	//获得文件后缀.png/.mp3
	suffix := c.DefaultPostForm("filetype", ".png")

	//初始化ossclient
	client, err := oss.New(ossConf.EndPoint, ossConf.AccessKeyId, ossConf.AccessKeySecret)
	if err != nil {
		RespFail(c, err.Error())
		return
	}
	//获得bucket
	bucket, err := client.Bucket(ossConf.Bucket)
	if err != nil {
		RespFail(c, err.Error())
		return
	}
	//设置文件名称
	//time.Now().Unix()
	filename := fmt.Sprintf("mnt/%d%04d%s",
		time.Now().Unix(), rand.Int31(),
		suffix)
	//通过bucket上传
	err = bucket.PutObject(filename, srcfile)
	if err != nil {
		RespFail(c, err.Error())
		return
	}
	//获得url地址
	url := "https://" + ossConf.Bucket + "." + ossConf.EndPoint + "/" + filename

	//响应到前端
	RespOk(c, url)
}
